<template>
  <view class="content">
    <view class="oneTitle font-12 px-3 py-2">
      请按照您最擅长的经营类目排序，系统会通过此顺序为您推荐相关订单和活动
    </view>
    <view class="top-table-title">
      <view class="sort-title table-title">排序</view>
      <view class="category table-title">类目</view>
      <view class="control-btn table-title">操作</view>
    </view>
    <movable-area :style="[getAreaStyle]">
      <movable-view
        v-for="(item, index) in list"
        :animation="animation"
        :direction="direction"
        :key="item.key"
        :damping="damping"
        :x="item.x"
        :y="item.y"
        :disabled="longpress ? disabled : false"
        @longpress="handleLongpress"
        @touchstart="handleDragStart(index)"
        @change="handleMoving"
        @touchend="handleDragEnd"
        :style="[getViewStyle]"
        class="base-drag-wrapper"
      >
        <view
          :class="{ 'base-drag-wrapper-active': activeIndex === index }"
          class="drag-item itemCells whiteColor drag-dl-main"
          style="width: 100%"
        >
          <view style="width: 100rpx">
            <view
              class="left-sort"
              :class="{
                first_sort: index == 0,
                two_sort: index == 1 || index == 2,
              }"
              >{{ index + 1 }}</view
            >
          </view>
          <view class="category-name">{{ item.name }}</view>
          <view class="right-icon">
            <u-icon name="list" size="24" color="#ededed"></u-icon>
          </view>
        </view>
      </movable-view>
    </movable-area>

    <view class="category-bottom">
      <view class="select-count" @click="handleUpStep">上一步</view>
      <view class="next-sort-btn" @click="handleNextSelectSkill"
        >下一步 选择技能</view
      >
    </view>
  </view>
</template>

<script>
export default {
  props: {
    column: {
      type: Number,
      default: 1,
    },
    value: {
      type: Array,
      default: () => [],
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "auto",
    },
    // itemKey: {
    //   type: String,
    //   required: true,
    // },
    itemHeight: {
      type: String,
      default: "50px",
    },
    direction: {
      type: String,
      default: "all",
      validator: (value) => {
        return ["all", "vertical", "horizontal", "none"].includes(value);
      },
    },
    animation: {
      type: Boolean,
      default: true,
    },
    damping: {
      type: Number,
      default: 20,
    },
    longpress: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      list: [
        { id: 1, name: "家具" },
        { id: 2, name: "锁类" },
        { id: 3, name: "电脑网络" },
        { id: 4, name: "办公设备" },
        { id: 5, name: "门" },
        { id: 6, name: "墙纸" },
        { id: 7, name: "窗帘" },
      ],
      disabled: true,
      activeIndex: -1,
      moveToIndex: -1,
      oldIndex: -1,
      tempDragInfo: {
        x: "",
        y: "",
      },
      cloneList: [],
    };
  },
  onLoad() {
    this.initList(this.list);
  },
  computed: {
    getAreaStyle() {
      const width = this.getRealWidth(this.width);
      return {
        width: width + "px",
        height:
          this.height !== "auto"
            ? this.height
            : Math.round(this.list.length / this.column) * this.getItemHeight +
              "px",
      };
    },
    getViewStyle() {
      const { itemHeight, getItemWidth } = this;
      return {
        width: getItemWidth + "px",
        height: itemHeight,
      };
    },
    getItemHeight() {
      return parseFloat(this.itemHeight);
    },
    getItemWidth() {
      if (this.column === 0) return;
      const width = this.getRealWidth(this.width);
      return (parseFloat(width) / this.column).toFixed(2);
    },
  },
  methods: {
    //拖拽中
    handleMoving(e) {
      if (e.detail.source !== "touch") return;
      const { x, y } = e.detail;
      Object.assign(this.tempDragInfo, {
        x,
        y,
      });

      const currentX = Math.floor(
        (x + this.getItemWidth / 2) / this.getItemWidth
      );
      const currentY = Math.floor(
        (y + this.getItemHeight / 2) / this.getItemHeight
      );

      this.moveToIndex = Math.min(
        currentY * this.column + currentX,
        this.list.length - 1
      );
      if (
        this.oldIndex !== this.moveToIndex &&
        this.oldIndex !== -1 &&
        this.moveToIndex !== -1
      ) {
        const newList = this.deepCopy(this.cloneList);
        let splicItem = newList.splice(this.activeIndex, 1)[0];
        newList.splice(this.moveToIndex, 0, splicItem);

        this.list.forEach((item, index) => {
          if (index !== this.activeIndex) {
            const itemIndex = newList.findIndex((val) => val.id === item.id);
            console.log(itemIndex);

            [item.x, item.y] = this.getPosition(itemIndex);
          }
        });
        this.oldIndex = this.moveToIndex;
      }
    },
    //拖拽结束
    handleDragEnd(e) {
      if (this.disabled) return;
      if (
        this.moveToIndex !== -1 &&
        this.activeIndex !== -1 &&
        this.moveToIndex !== this.activeIndex
      ) {
        console.log(this.cloneList);
        this.cloneList.splice(
          this.moveToIndex,
          0,
          ...this.cloneList.splice(this.activeIndex, 1)
        );
        console.log(this.cloneList, ">>");
      } else {
        this.$set(this.list[this.activeIndex], "x", this.tempDragInfo.x);
        this.$set(this.list[this.activeIndex], "y", this.tempDragInfo.y);
      }
      this.initList(this.cloneList);
      const endList = this.list.map((item) =>
        this.omit(item, ["x", "y", "key"])
      );
      this.$emit("input", endList);
      this.$emit("end", endList);

      this.activeIndex = -1;
      this.oldIndex = -1;
      this.moveToIndex = -1;
      this.disabled = true;
      this.$emit("handleDragEnd");
    },

    //获取当前的位置
    getPosition(index) {
      const x = (index % this.column) * this.getItemWidth;
      const y = Math.floor(index / this.column) * this.getItemHeight;
      return [x, y];
    },
    omit(obj, args) {
      if (!args) return obj;
      const newObj = {};
      const isString = typeof args === "string";
      const keys = Object.keys(obj).filter((item) => {
        if (isString) {
          return item !== args;
        }
        return !args.includes(item);
      });

      keys.forEach((key) => {
        if (obj[key] !== undefined) newObj[key] = obj[key];
      });
      return newObj;
    },
    initList(list = []) {
      const newList = this.deepCopy(list);
      this.list = newList.map((item, index) => {
        const [x, y] = this.getPosition(index);
        return {
          ...item,
          x,
          y,
          id: index + 1,
          key: Math.random() + index,
        };
      });
      this.cloneList = this.deepCopy(this.list);
    },
    deepCopy(source) {
      return JSON.parse(JSON.stringify(source));
    },
    //获取实际的宽度
    getRealWidth(width) {
      if (width.includes("%")) {
        const windowWidth = uni.getSystemInfoSync().windowWidth;
        width = windowWidth * (parseFloat(width) / 100);
      }
      return width;
    },
    //长按
    handleLongpress() {
      this.disabled = false;
    },

    //拖拽开始
    handleDragStart(index) {
      this.activeIndex = index;
      this.oldIndex = index;
    },

    onChange(e) {},

    // 下一步选择仅能
    handleNextSelectSkill() {
      console.log(this.cloneList, 'cloneList----');
      uni.navigateTo({
        url: '/pages/drawerPage/skill/selectSkill'
      })
    },
    // 上一步
    handleUpStep() {
      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss">
.content {
  background: #fff;
}
.oneTitle {
  color: #e19a6b;
  background-color: #fff0e9;
  box-sizing: border-box;
}
.top-table-title {
  margin-top: 30rpx;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  box-sizing: border-box;
  .sort-title {
    width: 100rpx;
  }
  .category {
    flex: 1;
  }
  .control-btn {
    width: 60rpx;
  }
  .table-title {
    font-size: 24rpx;
    color: #9e9b9b;
  }
}
.base-drag-wrapper {
  opacity: 1;
  z-index: 1;
  color: #212121;
  &.active {
    transform: scale(1.3);
    z-index: 99;
  }
}
.drag-dl-main {
  height: 52rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  .left-sort {
    font-size: 28rpx;
    color: #333;
    width: 50rpx;
    text-align: center;
    &.first_sort {
      padding: 6rpx 16rpx;
      background: #fcebe9;
      color: #d18a86;
      border-radius: 8rpx;
      box-sizing: border-box;
    }
    &.two_sort {
      padding: 6rpx 16rpx;
      background: #fdf7e2;
      color: #d9b973;
      border-radius: 8rpx;
      box-sizing: border-box;
    }
  }
  .category-name {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  .right-icon {
    width: 60rpx;
  }
}

.base-drag-wrapper-active {
  transform: scale(1.01);
  z-index: 999;
}

.item-wrap {
  position: relative;
}

.item-wrap .item {
  position: absolute;
  width: 100%;
  z-index: 1;
}

.item-wrap .item.itemTransition {
  transition: transform 0.3s;
}

.item-wrap .item.zIndex {
  z-index: 2;
}

.item-wrap .item.cur {
  transition: initial;
}

.item-wrap .item.fixed {
  z-index: 0 !important;
}

.info {
  position: relative;
  padding-top: 100%;
  background: #ffffff;
}

.info__item {
  position: absolute;
  border: 1rpx solid #ebedf0;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 10rpx;
  box-sizing: border-box;
}

.info__item .image {
  width: 100%;
  height: 100%;
}

.cell {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #ebedf0;
  background: #ffffff;
}

.cell__hd {
  font-size: 0;
}

.cell__hd .image {
  width: 160rpx;
  height: 160rpx;
  margin-right: 20rpx;
  border-radius: 12rpx;
}

.cell__bd {
  flex: 1;
}

.cell__bd .name {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  word-break: break-all;
  font-size: 28rpx;
  margin-bottom: 12rpx;
}

.cell__bd .des {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  word-break: break-all;
  color: #666666;
  font-size: 24rpx;
}

.itemCells {
  background-color: #fff;
  // border-radius: 8rpx;
  padding: 48rpx 32rpx;
  width: calc(100% - 144rpx);
  box-sizing: border-box;
  margin: 0 auto;
  border-bottom: 2rpx solid #eee;
}

.sort-num {
  margin-right: 16rpx;
}

.radio {
  width: 10px;
  height: 10px;
  border-radius: 20px;
  border: 1px solid #cccccc;
  margin-right: 10rpx;

  &.active-radio {
    position: relative;
    border-color: #447dff;
    border: 1px solid #447dff;

    &::after {
      content: "";
      width: 6px;
      height: 6px;
      position: absolute;
      right: 2px;
      top: 2px;
      background-color: #447dff;
      border-radius: 20px;
    }
  }
}

.icon-a-menu1 {
  color: #d9d9d9;
  font-size: 12px;
}

.category-bottom {
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  padding: 20rpx;
  gap: 32rpx;
  .select-count {
    width: 140rpx;
    color: #4ca9ec;
    font-size: 30rpx;
    padding-left: 30rpx;
  }
  .next-sort-btn {
    width: 480rpx;
    padding: 20rpx 0;
    text-align: center;
    background: #4ca9ec;
    color: #fff;
    font-size: 28rpx;
    border-radius: 12rpx;
  }
}
</style>
